﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MaxLeaf.Common;
using MaxLeaf.DB;
using System.Data;
using MySql.Data.MySqlClient;

namespace MaxLeaf.DAL.Web
{
    /// <summary>
    /// 物料
    /// </summary>
    public class ImInvMasterDAL : BaseDAL
    {
        private new  enum GetDataType
        {
            OrgT_icItem
            ,
            OrgT_ICItemCustom
                ,
            OrgCat_Name
                ,
            OrgUnit
            , Orgt_SubMessage

        }

        const string FIELDS = "cat_id,goods_sn,brand_id,goods_name,market_price,last_update,goods_img,modulus,FTypeID,xinghao,shop_price";
        public ImInvMasterDAL()
            : base()
        {
            strTableName = "mary_goods";
            strKeyFieldName = "FItemID";
            strFieldNames = FIELDS;
        }



        public override void Update(DBAccess dbOrgCon, DBAccess dbCon, string strKeyValue)
        {

            string strAddFieldNames = "FItemID";
            strFieldNames = FIELDS;



            string strFitemId = strKeyValue;
            DataTable dtData = dbCon.GetTableData(strTableName, new Dictionary<string, object> { { "FItemID", strFitemId } }, strAddFieldNames + ",goods_number,is_on_sale,is_use," + strFieldNames);
            DataRow drData = null;
            LogStatus logStatus = LogStatus.Update;

            DataRow drT_icItem = DAL_GetData(dbOrgCon, dbCon, (int)GetDataType.OrgT_icItem, strFitemId).Rows[0];


            if (dtData.Rows.Count == 0)
            {
                logStatus = LogStatus.Add;
                drData = dtData.NewRow();
                drData["FItemID"] = strFitemId;
                drData["is_on_sale"] = "0";
                strFieldNames = strAddFieldNames + "," + strFieldNames;
                strFieldNames = "is_on_sale" + "," + strFieldNames;
                drData["goods_number"] = "999";
                strFieldNames = "goods_number" + "," + strFieldNames;
                
            }
            else
            {
                drData = dtData.Rows[0];
                
            }

            if (CvtFunc.ToInt(drT_icItem["FDeleted"]) == 0)
            {
                drData["is_use"] = "1";
            }
            else
            {
                drData["is_use"] = "0";
            }
            strFieldNames = "is_use" + "," + strFieldNames;

           
            //if(drT_icItem==null)
            //{
            //    throw new MaxLeafException(string.Format("Fnumber {0} not exist on K3", drvLog[DEL.LogDEL.KeyValue]));
            //}

            //if (!CvtFunc.ToString(drData["goods_name"]).Equals(drT_icItem["FName"]))
            //{
            //    throw new MaxLeafException(string.Format("goods_name of Fnumber {1} on {0} not same as that on K3", dbCon drvLog[DEL.LogDEL.KeyValue]));
            //}



            string strItemParentFnumber = GetItemParentFnumber(drT_icItem);
            //分类有2中取法，funumber和f_136
            if (strItemParentFnumber.StartsWith("9."))
            {
                drData["cat_id"] = GetCat_id(dbOrgCon, dbCon, strItemParentFnumber, CvtFunc.ToString(drT_icItem["fnumber"]));
            }
            else
            {
                drData["cat_id"] = GetCat_idByf_136(dbOrgCon, dbCon, Getf_136(dbOrgCon, CvtFunc.ToString(drT_icItem["f_136"])), CvtFunc.ToString(drT_icItem["fnumber"]));
            }
            


            drData["goods_sn"] = drT_icItem["F_125"];
            drData["brand_id"] = GetBrand_id(dbCon, CvtFunc.ToString(drT_icItem["F_122"]));

            drData["goods_name"] = drT_icItem["FName"];
            //drData["goods_desc"] = drT_icItem["f_126"];
            //drData["goods_brief"] = drT_icItem["f_128"];

            //drData["goods_img"] = drT_icItem["f_127"];
            drData["modulus"] = drT_icItem["f_135"];
            //1、	请将K3中物料向网站传递的传送程序进行修改，物料分发不修改，将k3物料资料中编码以3和5开头的商品规格型号不传递到网站。修改范围：全国k3和全国网站
            if (!(strItemParentFnumber.StartsWith("3.") || strItemParentFnumber.StartsWith("5.")))
            {
                drData["xinghao"] = drT_icItem["FModel"];
            }
            //drData["danwei"] = ;

            drData["market_price"] = CvtFunc.ToDouble(drT_icItem["f_134"]);
            drData["shop_price"] = Getshop_price(dbOrgCon, drT_icItem);
            drData["last_update"] = CvtFunc.ToUnitStamp(DateTime.Now);

            if (CvtFunc.ToInt(drT_icItem["FTypeID"]) > 0)
            {
                //物料分类
                new mary_t_SubMessageDAL().Update(dbOrgCon, dbCon
                        , CvtFunc.ToString(drT_icItem["FTypeID"])
                    );
            }
            drData["FTypeID"] = drT_icItem["FTypeID"];

            KeyValuePair<string, IDataParameter[]> kvp = dbCon.CreateParamSql(strFieldNames, strTableName, drData, logStatus, strKeyFieldName);

            dbCon.ExecuteSql(kvp.Key, kvp.Value);

            //set 已分发
            KeyValuePair<string, IDataParameter[]> kvp138 = dbOrgCon.CreateCondParam(new Dictionary<string, object>() { { "FitemId", strFitemId } });
            dbOrgCon.ExecuteSql(string.Format("update t_icitemcustom set f_138=1 where {0}", kvp138.Key), kvp138.Value);

            //属性描述
            //{"产品描述",CvtFunc.ToString(drT_icItem["f_129"])}
            Dictionary <string, string>  dictattr=new Dictionary<string, string> 
                    { 
                        
                        {"颜色",CvtFunc.ToString(drT_icItem["F_124"])}
                        ,{"销售单位",CvtFunc.ToString(drT_icItem["f_140"])}
                        ,{"产品型号",CvtFunc.ToString(drT_icItem["FModel"])}                                               
                    };
            
            new mary_goods_attrDAL().Update(dbOrgCon, dbCon, CvtFunc.ToString(dbCon.GetTableDataFirstRow("mary_goods", new Dictionary<string, object> { { "FItemID", strFitemId } }, "goods_id")["goods_id"])
                , dictattr
            );

            
            
            
        }

        private string Getf_136(DBAccess dbOrgCon, string strf_136)
        {
            DataRow drData = dbOrgCon.GetTableDataFirstRow("t_SubMessage", new Dictionary<string, object> { { "FInterID", strf_136 } }, "fname");
            if (drData == null)
            {
                return string.Empty;
            }
            return CvtFunc.ToString(drData["fname"]);
        }

        private string GetCat_idByf_136(DBAccess dbOrgCon, DBAccess dbCon, string strgoods_brief,string strItemFnumber)
        {
            string[] arrgoods_brief = strgoods_brief.Split('_');
            string strCat_id = string.Empty;
            mary_categoryDAL catDal = new mary_categoryDAL();
            catDal.mstrItemFNumber = strItemFnumber;
            for (int i = 0; i < arrgoods_brief.Length; i++)
            {
                string strParentCat_id = "0";
                if (i != 0)
                {
                    strParentCat_id = strCat_id;
                }
                //得到每级的cat_id
                strCat_id = catDal.GetCat_id_ByName( dbCon, strParentCat_id, arrgoods_brief[i]);
            }




            return strCat_id;
        }

        private double  Getshop_price(DBAccess dbOrgCon, DataRow drT_icItem)
        {
//            string strSql = @"select t1.fnumber'物料代码',t1.fname'物料名称',t2.fname'销售单位',t2.fcoefficient'系数',t1.fsaleprice'基本单位单价'
//                        ,t1.fsaleprice * t2.fcoefficient as Shop_Price 
//                from t_icitem t1 inner join t_measureunit t2 on t1.f_140=t2.fmeasureunitid
//                where t1.fitemid=@fitemid
//            ";
            string strSql = @"select t1.fsaleprice * t2.fcoefficient as Shop_Price 
                            from t_icitem t1 inner join t_measureunit t2 on t1.FunitGroupID=t2.FunitGroupID  and t1.f_140=t2.FName
                            where t1.fitemid=@fitemid
                        ";
            KeyValuePair<string, IDataParameter[]> kvp = dbOrgCon.CreateCondParam(new Dictionary<string, object>() { { "fitemid",drT_icItem["fitemid"] } });
            DataRow drData = dbOrgCon.GetDataFirstRow(strSql, kvp.Value);
            if (drData == null)
            {
                throw new MaxLeafException(string.Format( "Fnumber {0} 不存在网站销售单位 {1}", drT_icItem["Fnumber"],CvtFunc.ToString( drT_icItem["f_140"])));
            }
            return CvtFunc.ToDouble(drData["Shop_Price"]);
        }

        private string GetItemParentFnumber(DataRow drT_icItem)
        {
            string strParentFnumber = CvtFunc.ToString(drT_icItem["Fnumber"]);
            
                int iEd=strParentFnumber.LastIndexOf('.');

                strParentFnumber = CvtFunc.ToLeftString(strParentFnumber, iEd);
            
            return strParentFnumber;
        }

        private string GetBrand_id(DBAccess dbCon, string strBrand_name)
        {
            mary_brandDAL brandDal = new mary_brandDAL();
            DataRow drBrand = dbCon.GetTableDataFirstRow( "mary_brand", new Dictionary<string, object> { { "brand_name", strBrand_name } }, "brand_id,brand_name");
 
            if (drBrand != null)
            {
                return CvtFunc.ToString(drBrand["brand_id"]);
            }
            return brandDal.Add(dbCon, strBrand_name);
        }



        private string GetCat_id(DBAccess dbOrgCon, DBAccess dbCon, string strFnumber, string strItemFnumber)
        {
            string[] arrFnumber = strFnumber.Split('.');
            string strCat_id = string.Empty;
            mary_categoryDAL catDal = new mary_categoryDAL();
            catDal.mstrItemFNumber = strItemFnumber;
            for (int i = 1; i < arrFnumber.Length; i++)
            {
                string strParentCat_id="0";
                if(i!=1)
                {
                    strParentCat_id=strCat_id;
                }
                //得到每级的cat_id
                strCat_id = catDal.GetCat_id(dbOrgCon, dbCon, strParentCat_id, string.Join(".", arrFnumber, 0, i + 1));
            }




            return strCat_id;

        }

        //private string GetCat_Name(DBAccess dbOrgCon,DBAccess dbCon, string[] arrFnumber, int i)
        //{
        //    string strFnumber = string.Join(".", arrFnumber, 0, i + 1);

        //    return CvtFunc.ToString(DAL_GetData(dbOrgCon,dbCon, (int)GetDataType.OrgCat_Name, strFnumber).Rows[0]["Fname"]);
        //}




        protected override DataTable DAL_GetData(DBAccess dbOrgCon, DBAccess destCon, int intdataType, object objParam)
        {
            GetDataType dataType = (GetDataType)intdataType;

            if (dataType == GetDataType.OrgT_icItem)
            {
                return GetT_icItem(dbOrgCon, CvtFunc.ToString(objParam));
            }
            else if (dataType == GetDataType.OrgT_ICItemCustom)
            {
                return GetT_ICItemCustom(dbOrgCon,CvtFunc.ToString(objParam));
            }
            else if (dataType == GetDataType.OrgCat_Name)
            {
                return GetCat_Name(dbOrgCon,CvtFunc.ToString(objParam));
            }
            else if (dataType == GetDataType.OrgUnit)
            {
                return GetUnit(dbOrgCon,CvtFunc.ToString(objParam));
            }
            else if (dataType == GetDataType.OrgUnit)
            {
                return GetUnit(dbOrgCon,CvtFunc.ToString(objParam));
            }
            else if (dataType == GetDataType.Orgt_SubMessage)
            {
                return Gett_SubMessage(dbOrgCon, CvtFunc.ToString(objParam));
            }


            return base.DAL_GetData(dbOrgCon, destCon, intdataType, objParam);
        }


        private DataTable GetUnit(DBAccess dbOrgCon, string strFMeasureUnitID)
        {
            return  dbOrgCon.GetTableData("t_MeasureUnit", new Dictionary<string, object> { { "FMeasureUnitID", strFMeasureUnitID } }, "FName");

        }

        
        private DataTable GetT_icItem(DBAccess dbOrgCon,string strFitemID)
        {

            DataTable dtT_icItem = null;
            if (dtT_icItem == null)
            {
                dtT_icItem = dbOrgCon.GetTableData("T_icItem", new Dictionary<string, object> { { "FItemID", strFitemID } }, "FItemID,Fnumber,FName,F_105,F_102,F_104,FSaleUnitID,f_140,FModel,F_108,fSalePrice,F_126,F_124,F_122,F_125,f_128,f_127,f_129,ftypeid,F_136,f_131,f_134,f_135,FDeleted");

            }
            return dtT_icItem;
        }

        DataTable dtT_ICItemCustom = null;
        private DataTable GetT_ICItemCustom(DBAccess dbOrgCon, string strFItemID)
        {

            if (dtT_ICItemCustom == null)
            {
                dtT_ICItemCustom = dbOrgCon.GetTableData("T_ICItemCustom", new Dictionary<string, object> { { "FItemID", strFItemID } });

            }
            return dtT_ICItemCustom;
        }

        private DataTable GetCat_Name(DBAccess dbOrgCon, string strFNumber)
        {
            return  dbOrgCon.GetTableData("T_Item", new Dictionary<string, object> { { "fnumber", strFNumber }, { "FItemClassID", "4" } }, "FName");

        }

        private DataTable Gett_SubMessage(DBAccess dbOrgCon, string strFInterID)
        {
//            string strSql = @"SELECT        a1.FTypeID, a1.FName, a1.FDetail, a1.FType, a1.FGRType,  a1.UUID
//            , a2.FBrNo, a2.FInterID, a2.FID, a2.FParentID, a2.FName AS FName_m, 
//                         a2.FTypeID AS FTypeID_m, a2.FDetail AS FDetail_m, a2.FDeleted,  a2.FSystemType, a2.FSpec, a2.UUID AS UUID_m
//            FROM            t_SubMesType AS a1 INNER JOIN
//                                     t_SubMessage AS a2 ON a1.FTypeID = a2.FTypeID
//            where a2.FInterID=@FInterID
//              order by  a1.FTypeID,a2.FInterID";

                string strSql = @"SELECT a2.FBrNo, a2.FInterID, a2.FID, a2.FParentID, a2.FName, 
                         a2.FTypeID  , a2.FDetail , a2.FDeleted,  a2.FSystemType, a2.FSpec, a2.UUID
            FROM            t_SubMesType AS a1 INNER JOIN
                                     t_SubMessage AS a2 ON a1.FTypeID = a2.FTypeID
            where a2.FInterID=@FInterID
              order by  a1.FTypeID,a2.FInterID";
            KeyValuePair<string,IDataParameter[]> kvp= dbOrgCon.CreateCondParam(new Dictionary<string,object>(){{"FInterID",strFInterID}});
            return  dbOrgCon.GetDataTable(strSql,kvp.Value); 

        }
        

        

        
    }
}